//
//  PhotoManager.m
//  JBPlatform
//
//  Created by yanhuilv on 16/7/24.
//  Copyright © 2016年 yanhuilv. All rights reserved.
//

#import "PhotoManager.h"
#import "VPImageCropperViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "TZImagePickerController.h"
#import "LGTImagePickerVC.h"

#define ORIGINAL_MAX_WIDTH 640.0f

@interface PhotoManager()<UINavigationControllerDelegate,UIImagePickerControllerDelegate, VPImageCropperDelegate, TZImagePickerControllerDelegate>

@property (assign, nonatomic) UIImagePickerControllerSourceType imageType;

@end

@implementation
PhotoManager


#pragma mark VPImageCropperDelegate
//- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
//    [_delegate imageCropper:cropperViewController didFinished:editedImage];
//}

- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    [_delegate imageCropper:cropperViewController didFinished:editedImage];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [_delegate imageCropperDidCancel:cropperViewController];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            
            [controller.navigationBar setBarTintColor:[UIColor redColor]];
            controller.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
            controller.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
            controller.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
            [_delegate finish:controller];
        }
        
        self.imageType = UIImagePickerControllerSourceTypeCamera;
        
    } else if (buttonIndex == 1) {
        self.imageType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            //WKImagePickerController.h
            CGSize size = [UIScreen mainScreen].bounds.size;
            LGTImagePickerVC *imageVC = [[LGTImagePickerVC alloc] initWithMaxImagesCount:1 delegate:self];
            imageVC.allowPickingVideo = NO;
            imageVC.allowPreview = NO;
            imageVC.alwaysEnableDoneBtn = NO;
            imageVC.allowCrop = YES;
            imageVC.showSelectBtn = NO;
            imageVC.cropRect = CGRectMake(0, (size.height - size.width)/2, size.width, size.width);
            if(self.maxImageCount > 0){
                imageVC.maxImagesCount = self.maxImageCount;
            }
            
            
            //原生的
//            SMImagePickerController *controller = [[SMImagePickerController alloc] init];
//            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
//            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
//            controller.mediaTypes = mediaTypes;
//            controller.delegate = self;
//            
//            [controller.navigationBar setBarTintColor:KNavColor];
//            controller.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:KMainWhite};
            
//            controller.navigationItem.rightBarButtonItem.tintColor = KMainRed;
//            controller.navigationItem.leftBarButtonItem.tintColor = KMainRed;
            [_delegate finish:imageVC];
        }
    }
}

#pragma mark TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    
    if(self.needImages == YES){
        
        if ([_delegate respondsToSelector:@selector(imageCropperSelectImages:sourceAssets:)]){
            [_delegate imageCropperSelectImages:photos sourceAssets:assets];
        }
        return;
    }

    
    //裁剪视图
    UIImage *portraitImg = photos[0];
    //不需要裁剪
    if(self.unNeedCrop == true){
        //不需要裁剪
        if(self.unNeedCrop == true){
            [self imageCropper:nil didFinished:portraitImg];
            return;
        }
        return;
    }
    
    VPImageCropperViewController *imgCropperVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:[_delegate getCropSize] limitScaleRatio:3];
    imgCropperVC.delegate = self;
    [_delegate finish:imgCropperVC];
    
    
    //    [picker dismissViewControllerAnimated:YES completion:^() {
    //        UIImage *portraitImg = photos[0];
    //        portraitImg = [self imageByScalingToMaxSize:portraitImg];
    //        // present the cropper view controller
    //        VPImageCropperViewController *imgCropperVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:[_delegate getCropSize] limitScaleRatio:3.0];
    //        imgCropperVC.delegate = self;
    //        [weakSelf.delegate finish:imgCropperVC];
    //    }];
    
    //    UIImage *portraitImg = photos[0];
    //    [_delegate imageCropper:(VPImageCropperViewController *)picker didFinished:portraitImg];
    
    //[_delegate imageCropper:(VPImageCropperViewController *)picker didFinished:portraitImg];
    
//    UIImage *portraitImg = photos[0];
//    portraitImg = [self imageByScalingToMaxSize:portraitImg];
//    // present the cropper view controller
//    VPImageCropperViewController *imgCropperVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:[_delegate getCropSize] limitScaleRatio:3.0];
//    imgCropperVC.delegate = self;
//    [self.delegate finish:imgCropperVC];
    
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    __weak typeof(self) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        //不需要裁剪
        if(weakSelf.unNeedCrop == true){
            [_delegate imageCropper:nil didFinished:portraitImg];
            return;
        }
        
        // present the cropper view controller
        VPImageCropperViewController *imgCropperVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:[_delegate getCropSize] limitScaleRatio:3];
        imgCropperVC.delegate = self;
        [_delegate finish:imgCropperVC];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    bool type = picker.sourceType == UIImagePickerControllerSourceTypeCamera ? YES : NO;
    
    [picker dismissViewControllerAnimated:YES completion:^(){
        NSString *message = @"选择图片失败";
        if(type == YES){
            message = @"拍照失败";
        }
       // [SVProgressHUD showErrorWithStatus:message];
    }];
}

- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker{
    
    bool type = self.imageType == UIImagePickerControllerSourceTypeCamera ? YES : NO;
    NSString *message = @"选择图片失败";
    if(type == YES){
        message = @"拍照失败";
    }
    //[SVProgressHUD showErrorWithStatus:message];
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark - UINavigationControllerDelegate

//设置 UIImagePickerController 左右导航条颜色
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
//    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
//    viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
//    NSDictionary *textAttr = @{NSForegroundColorAttributeName:KMainWhite};
//    [viewController.navigationItem.leftBarButtonItem setTitleTextAttributes:textAttr forState:UIControlStateNormal];
//    [viewController.navigationItem.rightBarButtonItem setTitleTextAttributes:textAttr forState:UIControlStateNormal];
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
//    NSDictionary *textAttr = @{NSForegroundColorAttributeName:KMainWhite};
//    [viewController.navigationItem.leftBarButtonItem setTitleTextAttributes:textAttr forState:UIControlStateNormal];
//    [viewController.navigationItem.rightBarButtonItem setTitleTextAttributes:textAttr forState:UIControlStateNormal];
//    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
//    [backBtn setBackgroundColor:KMainOrange];
//    viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

@end
